// pages/pay/pay.js
Page({

  data: {
    // 配送方式
    array: ['请选配送方式', '院内配送', '院内自取'],
    selectedIndex: 1,
    // 选择院区
    array2: [], //['选择院区', '增城院区']
    idDataMap: {}, // 用于保存id和对应数据的映射关系
    selectedObject: null,
    selectedCoupon: null,
    showPicker: false, // 显示选择器
    // 选择楼层
    array3: [],
    showPicker3: false,
    //  '选择楼层', '门诊一楼', '门诊二楼', '门诊三楼', '门诊四楼', '门诊五楼', '负一层', '感染楼二层', '住院部二楼', '住院部三楼', '住院部四楼', '住院部五楼', '住院部六楼', '住院部七楼', '住院部八楼', '住院部九楼', '住院部十楼', '住院部十一楼', '住院部十二楼', '行政楼'
    array6: [], //科室
    showPicker4: false,
    idDataMap4: {},
    selectedObject4: null,
    array5: [], //楼层
    showPicker5: false,
    specMultipleValue: '',
    judgment: false,
    index: 0,
    //  院内选择
    index2: 0,
    index3: 0,
    index6: 0,
    index5: 0,
    xndex5: 0,
    isRightTime: false,
    canCoupon: '',
    productStatus: '',
    // 选择送货时间
    multiArray: [
      ['日期', '今日', '明日'],
      ['时间']
    ],
    multiIndex: [0, 0, 0],
    TopIndex: 0, //隐藏显示界面
    // 自提时间
    array4: ['时间', '9:05', '10:45', '11:05', '12:45', '13:45', '14:05', '15:45', '16:05', '17:45', '18:05'],
    index4: 0,
    markers: [],
    latitude: 0,
    longitude: 0,
    scale: 16,
    address: '',
    doderaddress: '',
    //定义数组用来储存本地获取到的数据
    cart: '',
    //储存商品总价格
    price: 0,
    //储存门店ID
    storeID: 0,
    prices: 0,
    specification: '',
    //储存门店信息
    mendian: '',
    //储存输入的床号
    inputValue1: '',
    //储存输入的详细地址
    inputValue: '',
    //储存输入的电话号码
    phone: '',
    //储存收件人名称
    name: '',
    //储存给商家留言
    messg: ' ',
    //储存用户信息的数组
    userAddress: '',
    //判断是否存在默认地址，0表示不存在。1表示存在
    jgnum: false,
    containerHeight: 'auto',
    // 用户获取用户的优惠券信息存放
    orderCoupon: [],
    finalPrice: 0,
    // 会员价
    memberPrice: 0,
    member: 0,
    // 会员价小计显示的价格
    priceMember: 0,
    priceMembers: 0,
    loading: false,
    categoriesId: '',
    pangd: true,
    courtyardId: '',
    departmentId: '',
    floorId: '',
    serviceTel: '' // 用于存储商家电话
  },

  // 配送方式
  optionChange: function (e) {
    console.log(e)
    if (e !== undefined) {
      this.setData({
        selectedIndex: e.detail.value
      });
    }

    let that = this;
    wx.request({
      url: 'https://199shq.com/api/wxCoupons/getCourtyard',
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data); // 处理返回的数据
        let idDataMap = {};
        let newData = res.data.map(item => {
          idDataMap[item.id] = item; // 将id和对应数据存入idDataMap
          return item.name; // 只保留院区名称
        });
        that.setData({
          array2: res.data,
          idDataMap: idDataMap,
        });
        that.findaddress()
      },
      fail: function (error) {
        console.log(error);
      }
    });

  },


  //  院内选择
  bindPicker2Change: function (e) {
    const index = e.detail.value; // 获取用户选择的索引
    const selectedName = this.data.array2[index].name; // 获取选中的院区名称

    console.log('Selected Name:', selectedName); // 输出选中的院区名称
    console.log('idDataMap:', this.data.idDataMap); // 输出idDataMap的内容

    const selectedObject = Object.values(this.data.idDataMap).find(obj => obj.name === selectedName);
    console.log(selectedObject);
    if (selectedObject) {
      this.setData({
        index2: index,
        showPicker: true, // 显示已选中的院区名称
        selectedObject: selectedObject, // 存储选中的对象
        courtyardId: selectedObject.id
      });
      const id = this.data.selectedObject.id;
      let that = this;
      // 科室选择
      wx.request({
        url: `https://199shq.com/api/wxCoupons/getDepartment/` + id, //备注带data这里不需要${addressId}
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          console.log(res.data); // 输出返回的数据，确保其是否为数组
          if (Array.isArray(res.data)) {
            let idDataMap4 = {};
            let newData4 = res.data.map(item => {
              idDataMap4[item.id] = item; // 将id和对应数据存入idDataMap
              return item.departmentName; // 只保留院区名称
            });
            that.setData({
              array6: res.data,
              idDataMap4: idDataMap4,
            });
            console.log("idDataMap4数据");
            console.log(idDataMap4)
          } else {
            console.log("返回的数据不是数组，无法进行 map 操作");
            // 可以根据实际情况进行其他处理，比如给出提示或执行其他操作
          }
        },
        fail: function (error) {
          console.log(error); // 请求失败的处理
        }
      });
    } else {
      // 处理选中对象无效的情况，比如给出提示或执行其他操作
      console.log("选中对象无效");
    }
  },

  // handleTap: function () {
  //   // 在这里编写触发事件后的逻辑代码
  //   console.log('点击触发了事件');
  //   this.setData({
  //     showPicker: true
  //   })
  // },
  // 科室选择
  bindPicker4Chang: function (e) {
    const index = e.detail.value;
    console.log("index：" + index)
    const selectedName = this.data.array6[index].departmentName;
    console.log('Selected Name:', selectedName); // 输出选中的院区名称
    console.log(this.data.idDataMap4); // 输出idDataMap的内容
    if (typeof selectedName !== 'undefined') {
      const selectedObject4 = Object.values(this.data.idDataMap4).find(obj => obj.departmentName === selectedName);
      console.log(selectedObject4);

      this.setData({
        index6: e.detail.value,
        selectedObject4: selectedObject4,
        departmentId: selectedObject4.id // 将选中的科室信息保存到页面数据中的 selectedDepartment 中
      });
      //楼层
      // 获取选中的科室和楼层关联id
      const id = this.data.selectedObject4.id;

      console.log("获取到的关联的科室和楼层关联id::" + id);
      let that = this;

      wx.request({
        url: `https://199shq.com/api/wxCoupons/getFloor/` + id,
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          console.log("楼层信息")
          console.log(res.data); // 处理返回的数据
          let newData = res.data.map(item => item.number); // 提取每个对象的 name 属性
          that.setData({
            array3: res.data,
            floorId: res.data[0].id
          });
        },
        fail: function (error) {
          console.log(error); // 请求失败的处理
        }
      });
    } else {

      wx.showToast({
        title: '请先选择院内',
        icon: 'none',
        duration: 2000
      });
    }

  },
  handle4: function () {

    this.setData({
      showPicker4: true,
    })
  },



  // 楼层---------------------------------
  bindPicker3Change: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index3: e.detail.value
    })
  },
  handleTap3: function () {
    // 在这里编写触发事件后的逻辑代码
    this.setData({
      showPicker3: true,
    })
  },

  // // 床号
  // bindPicker5Change: function (e) {
  //   this.setData({
  //     index5: e.detail.value,

  //   })
  // },
  // handleTap5: function () {
  //   // 在这里编写触发事件后的逻辑代码
  //   console.log('点击触发了事件');
  //   this.setData({
  //     showPicker5: true
  //   })
  // },
  /**
   */




  // 送达时间
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },

  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e, '，值为', e.detail.value);
    this.data.array4[i] = []
    // console.log(this.data.array4[i])
    if (e.detail.column == 0 && e.detail.value == 0) {
      this.data.multiArray[1] = [];
    } else if (e.detail.column == 0 && e.detail.value == 1) {
      console.log('进入了这里1')
      var timeNum = new Date().toTimeString().substring(0, 5).replace(":", "");
      var tempTimeArr = [];
      for (var i = 1; i < this.data.array4.length; i++) {
        var tempTimeNum = this.data.array4[i].replace(":", "");
        console.log(tempTimeNum)
        console.log(timeNum)
        if (Number(tempTimeNum) > Number(timeNum)) {
          tempTimeArr.push(this.data.array4[i]);
          console.log(tempTimeArr)
        }
      }

      this.data.multiArray[1] = tempTimeArr;
      console.log(this.data.multiArray[1])
    } else if (e.detail.column == 0 && e.detail.value == 2) {
      console.log('进入了这里')
      this.data.multiArray[1] = this.data.array4;
    }
    this.setData({
      multiArray: this.data.multiArray
    });
    // 知道修改的列以后，就可以通过修改multiIndex中对应元素的值，然后再修改multiArray
  },
  // 自提时间
  bindPicker4Change: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index4: e.detail.value
    })
  },
  // 界面隐藏显示
  changstyle: function (e) {
    let index = e.currentTarget.dataset.index; /*定义index等于当前页面的dataset.index*/
    this.setData({
      TopIndex: index /*定义当前数据的TopIndex等于  index 等于dataset.index*/
    })
  },
  onAddressClick() {
    wx.navigateTo({
      url: '/pages/map/map',
    })
  },
  // 定位
  //    onAddressClick() {
  //     const address = this.data.address; // 获取点击的地址
  //     wx.request({
  //       url: 'https://apis.map.qq.com/ws/geocoder/v1/',
  //       data: {
  //         address: address,
  //         key: 'NCLBZ-6X5LZ-7KAXO-TCS7S-RFMNZ-KVBH4'
  //       },
  //       success: (res) => {
  //         const result = res.data.result;
  //         const location = result.location;

  //         this.setData({
  //           latitude: location.lat,
  //           longitude: location.lng,
  //           markers: [{
  //             id: 0,
  //             latitude: location.lat,
  //             longitude: location.lng,
  //             iconPath: '/images/定位.png',
  //             width: 30,
  //             height: 30
  //           }]
  //         });

  //         // 调用导航接口
  //         wx.openLocation({
  //           latitude: location.lat,   // 目标纬度
  //           longitude: location.lng,  // 目标经度
  //           name: address,            // 目标名称
  //           scale: 18                // 缩放级别，范围1-28，默认为18
  //         });
  //       },
  //       fail: (res) => {
  //         console.error(res);
  //       }
  //     });

  // },
  /*wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/',
          data: {
            address: address,
            key: 'NCLBZ-6X5LZ-7KAXO-TCS7S-RFMNZ-KVBH4'
          },
          success: (res) => {
            const result = res.data.result;
            const location = result.location;
            
            this.setData({
              latitude: location.lat,
              longitude: location.lng,
              markers: [{
                id: 0,
                latitude: location.lat,
                longitude: location.lng,
                iconPath: '/images/定位.png',
                width: 30,
                height: 30
              }]
            });
          },
          fail: (res) => {
            console.error(res);
          }
        });
      },
    
      onMarkerTap(e) {
        const markerId = e.detail.markerId;
    
        // 点击标记点后的逻辑处理
        // 可以根据需求自行扩展
      },*/


  //从购物车传递数据过来,从本地获取出来
  getSSnc: function () {
    var app = getApp();
    var user_id = String(app.globalData.userInfo.wxUserId);
    var cart = wx.getStorageSync(user_id);
    console.log("从购物车传递数据过来,从本地获取出来");
    console.log(cart);
    var pangd = true
    for (let i = 0; i < cart.length; i++) {
      // const element = array[i];
      if (cart[i].categoriesId == 17840479) {
        pangd = false
      }
    }
    // 自动判断配送方式
    let selectedIndex = this.data.selectedIndex; // 默认保持当前值

    // 只有当 cart 存在且为数组时才判断
    if (Array.isArray(cart) && cart.length > 0) {
      //院内配送
      const hasDelivery = cart.some(item => item.categoriesId === 711460724);
      // 院内自取
      const hasPickup = cart.some(item =>
        item.categoriesId === 1032926999 ||
        item.categoriesId === 1264551100 ||
        item.categoriesId === 206457979  ||
        item.categoriesId === 1719551306
      );

      if (hasDelivery) {
        selectedIndex = 1; // 院内配送
      } else if (hasPickup) {
        selectedIndex = 2; // 院内自取
      }
      // 否则保持原 selectedIndex（比如 0：请选配送方式）
    }

    // --- 最终统一 setData ---
    this.setData({
      cart: cart,
      pangd: pangd,
      selectedIndex: selectedIndex // 新增：自动设置配送方式
    })
  },

  //计算商品价格和商品的数量并进行展示
  countprice: function () {
    //获取到用户的userid
    var app = getApp();
    var user_id = String(app.globalData.userInfo.wxUserId);
    //获取并计算出商品的总价格进行保存
    var price = wx.getStorageSync(user_id);
    // console.log(price);
    var total_price = 0,
      total_quantity = 0;
    console.log(price)
    for (var i = 0; i < price.length; i++) {
      total_price += price[i].cartprice * price[i].quantity;
      total_quantity += price[i].quantity;
      console.log(price[i].quantity)
    }
    // 默认的总价
    // this.setData({
    //   price: total_price.toFixed(2)
    // })selectedIndex
    this.setData({
      price: total_price.toFixed(2),
      // priceMember: total_price.toFixed(2),
    })
    // 判断是否是会员
    const userInfo = wx.getStorageSync('userInfo');
    var userId = userInfo.wxUserId;
    var that = this;

    wx.request({
      url: `https://199shq.com/api/wxuser/getMembershipPrice/` + encodeURIComponent(userId),
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        const data = res.data.data;
        console.log(res.data.data);
        const memberPrice = res.data.data.memberPrice;
        console.log(memberPrice, this.data.prices);
        that.setData({
          memberPrice: memberPrice,
          member: data.member, // 判断member是否为1 1是会员 0不是会员 2申请中
        });
        console.log(total_price, memberPrice)
        let num = Number(memberPrice);
        console.log(num)
        if (total_price > num) {
          // 请求成功后进行价格计算和设置
          const member = data.member;
          console.log("执行这个理" + total_price + num)
          console.log(member);
          // 简化条件判断并计算价格
          total_price = member === 1 ? total_price * num : total_price;
          console.log("会员价2");
          console.log(total_price);
          // 设置价格
          that.setData({
            priceMember: total_price.toFixed(2),
            priceMembers: total_price.toFixed(2),
            price: total_price.toFixed(2)
          });
          console.log('jirn')
        } else {
          total_price = (parseFloat(total_price)).toFixed(2)
          // 默认的总价
          console.log(total_price)
          this.setData({
            priceMember: total_price,
            priceMembers: total_price,
            price: total_price.toFixed(2)
          })
        }
      },
      fail: (error) => {
        console.log(error); // 请求失败的处理
      }
    });



  },

  //获取门店的背景图片和头像
  getMendian: function () { //定义函数名称
    var that = this;
    let b = this.data.storeID;
    let prices = this.data.prices
    console.log(prices)
    wx.request({
      url: `https://199shq.com/api/stores/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data);
        var list = res.data.data;
        if (list == null) {
          wx.showToast({
            title: '数据获取失败',
            icon: 'none',
            duration: 2000
          });
        } else {
          that.setData({
            mendian: res.data.data
          })
        }
      }
    })
  },

  //定义函数用于监听输入的详细地址
  inputChange: function (e) {
    var inputValue = e.detail.value;
    console.log(inputValue); // 输出输入框的值
    this.setData({
      inputValue: inputValue
    })
  },

  //定义函数用于监听输入的电话号码
  getPhone: function (e) {
    var phone = e.detail.value;

    if (phone === '') {
      this.setData({
        phone: ''
      })
      // 电话号码为空，不进行校验
      return;
    }

    if (phone.length !== 11) {
      // 电话号码长度不正确
      wx.showToast({
        title: '请输入11位电话号码',
        icon: 'none'
      });
      return;
    }

    var reg = /^1[3456789]\d{9}$/;
    if (!reg.test(phone)) {
      // 电话号码格式不正确
      wx.showToast({
        title: '请输入正确的电话号码',
        icon: 'none'
      });
      return;
    }

    // 电话号码校验通过
    this.setData({
      phone: phone
    });
  },

  //定义函数用于货物收件人名称
  getName: function (e) {
    var name = e.detail.value;
    console.log(name);
    var reg = /^[\u4e00-\u9fa5a-zA-Z]+$/;
    if (reg.test(name)) {
      // 姓名格式正确
      this.setData({
        name: name
      });
    } else {
      // 姓名格式不正确
      wx.showToast({
        title: '请输入合法的姓名',
        icon: 'none'
      });
      this.setData({
        name: ''
      });
    }
  },

  //定义函数用于获取给商家留言
  getMessg: function (e) {
    var messg = e.detail.value;
    var reg = /^[\u4e00-\u9fa5]+$/;
    if (reg.test(messg)) {
      // 消息内容格式正确
      this.setData({
        messg: messg
      });
    } else {
      // 消息内容格式不正确
      wx.showToast({
        title: '请输入汉字',
        icon: 'none'
      });
    }
  },

  //定义函数获取到配送时间
  getDistribution: function () {
    var multiArray1 = this.data.multiArray[0];
    var multiArrayIndex1 = this.data.multiIndex[0];
    console.log(multiArray1[multiArrayIndex1]);
    if (multiArray1[multiArrayIndex1] == '日期') {
      return multiArray1[multiArrayIndex1]
    }
    var now = new Date();
    var year = now.getFullYear();
    if (multiArray1[multiArrayIndex1] == '今日') {
      //获取到今日日期
      var month = now.getMonth() + 1;
      var day = now.getDate();
      var adddate = year + '-' + month + '-' + day;
      console.log(adddate);
    } else {
      //获取到明天日期
      var month = now.getMonth() + 1;
      var day = now.getDate() + 1;
      var adddate = year + '-' + month + '-' + day;
      console.log(adddate);
    }
    var multiArray2 = this.data.multiArray[1];
    var multiArrayIndex2 = this.data.multiIndex[1];
    console.log(multiArray2[multiArrayIndex2]);
    if (multiArray2[multiArrayIndex2] == '时间') {
      return multiArray2[multiArrayIndex2]
    }

    var nowSelect = new Date(adddate + ' ' + multiArray2[multiArrayIndex2]);

    if (nowSelect >= now) {
      this.data.isRightTime = true;
    }
    return adddate + '-' + multiArray2[multiArrayIndex2];
  },


  //订单提交成功后清空购物车
  removeStorageSync: function () {
    var app = getApp();
    var user_id = String(app.globalData.userInfo.wxUserId);
    // 清除缓存数据
    wx.removeStorageSync(user_id);
  },
  Submitorder: function () {
    var isCanApply = false;
    var TopIndex = this.data.TopIndex;
    const that = this

    // 获取购物车数据
    const cart = this.data.cart || [];

    // 检查是否有需要10：00前下单的商品
    const hasEarlyOrderItem = cart.some(item =>
      item.specification && item.specification.includes("10:00前下单")
    );

    // 如果存在这类商品，检查当前时间是否已过 10:00
    if (hasEarlyOrderItem) {
      const now = new Date();
      const currentHour = now.getHours();
      const currentMinute = now.getMinutes();
      const isAfterDeadline = currentHour > 10 || (currentHour === 10 && currentMinute >= 0); // 10:00 后不允许

      if (isAfterDeadline) {
        wx.showModal({
          title: '无法提交订单',
          content: '该商品需要在10:00前下单，当前已过下单时间，无法提交订单。',
          showCancel: false
        });
        return false;
      }
    }

    // 获取 mendian.name
    const deliveryType = this.data.mendian?.name;
    console.log('配送类型:', deliveryType); // 调试用

    // 获取当前时间
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    const isAfterDeadline = currentHour > 16 || (currentHour === 16 && currentMinute >= 0); // 16:00 后不允许下单

    // 如果是“今日配送”且已过下午4点，则禁止提交
    if (deliveryType === '今日配送' && isAfterDeadline) {
      wx.showModal({
        title: '无法提交订单',
        content: '今日配送已截止（16:00截止），请选择次日配送商品继续下单。',
        showCancel: false
      });
      return false;
    }

    if (TopIndex == 0) {
      //获取到配送方式
      var array = this.data.array;
      var index = this.data.selectedIndex;
      var Distribution = array[index];
      console.log(Distribution); //string  y

      // 获取当前时间
      const currentDate = new Date();
      // 获取当前小时数
      const currentHour = currentDate.getHours();

      // 判断是否在晚上八点之后
      const isAfterSix = currentHour >= 20;
      console.log(isAfterSix)
      if (isAfterSix) {
        wx.showModal({
          title: '提示',
          content: '已过订单时间，晚上八点后暂不支持订餐',
          showCancel: false
        });
        return false
      }
      if (Distribution == '请选配送方式') {
        wx.showModal({
          title: '提示',
          content: '请选择配送方式',
          showCancel: false
        });
        return false;
      } else if (Distribution == '院内配送') {
        //获取到选择院区
        var arr2 = this.data.array2;
        var index2 = this.data.index2;
        if (arr2[index2].name == '选择院区') {
          wx.showModal({
            title: '提示',
            content: '请选择院区',
            showCancel: false
          });
          return false;
        }
        //获取到选择科室
        var arr6 = this.data.array6;
        var index6 = this.data.index6;
        if (arr6[index6].departmentName == '选择科室') {
          wx.showModal({
            title: '提示',
            content: '请选择科室',
            showCancel: false
          });
          return false;
        }
        //获取到选择楼层
        var arr5 = this.data.array5;
        var index5 = this.data.index5;
        if (arr5[index5] == '选择楼层') {
          wx.showModal({
            title: '提示',
            content: '请选择楼层',
            showCancel: false
          });
          return false;
        }
        //获取送达的楼层
        var arr3 = this.data.array3;
        var index3 = this.data.index3;
        if (arr3[index3].number == '选择楼层') {
          wx.showModal({
            title: '提示',
            content: '请选择楼层',
            showCancel: false
          });
          return false;
        }
        //获取到输入详细地址
        var input = this.data.inputValue;
        console.log(input);
        if (input == '') {
          wx.showModal({
            title: '提示',
            content: '请填写详细的地址',
            showCancel: false
          });
          console.log(input)
          return false;
        }
        //储存订单的地址
        var doderaddress = arr2[index2].name + '-' + arr6[index6].departmentName + '-' + arr3[index3].number + '-' + input;
        console.log(doderaddress); //string  y
        this.setData({
          doderaddress: doderaddress
        });
        //获取到收件人名称
        var name = this.data.name;
        if (name == '') {
          wx.showModal({
            title: '提示',
            content: '请填写收件人的名称',
            showCancel: false
          });
          return false;
        }
        console.log(name); //string y

        //获取输入的电话号码
        var phone = this.data.phone;
        if (phone == '') {
          wx.showModal({
            title: '提示',
            content: '请填写电话号码',
            showCancel: false
          });
          console, log(phone)
          return false;
        }
        var reg = /^1[3456789]\d{9}$/;
        //用正则表达式验证电话号码是否合格
        if (!reg.test(phone)) {
          wx.showModal({
            title: '提示',
            content: '请填写正确的电话号码',
            showCancel: false
          });
          return false;
        }
        console.log(phone); //string  y

        //获取到配送时间
        var date = this.getDistribution();
        // if (date == '日期' || date == '时间') {
        //   wx.showModal({
        //     title: '提示',
        //     content: '请选择合适的送达时间',
        //     showCancel: false
        //   });
        //   return false;
        // }
        // if (!this.data.isRightTime) {
        //   wx.showModal({
        //     title: '提示',
        //     content: '请选择正确的送达时间',
        //     showCancel: false
        //   });
        //   return false;
        // }
        console.log(date); //string

        isCanApply = true;
        var pangd = this.data.pangd
        // 在 wx.showModal 前判断并设置提示语
        let deliveryMsg = '订单将按时送达'; // 默认兜底文案

        if (deliveryType === '今日配送') {
          deliveryMsg = '今日订的餐将今日送达';
        } else if (deliveryType === '次日配送') {
          deliveryMsg = '今日订的餐将次日送达';
        }

        // if (pangd) {
        wx.showModal({
          title: '提示',
          content: deliveryMsg,
          success(res) {
            console.log(res)
            if (res.confirm) {
              // 用户点击了确定按钮
              that.postOrder()
              that.addaddress()
              // 这里可以添加点击确定后的逻辑代码，比如重新让用户输入电话号码等
            } else if (res.cancel) {
              // 用户点击了取消按钮
              console.log('用户点击了取消');
              // 这里可以添加点击取消后的逻辑代码，比如关闭弹窗，不做其他操作等
            }

          },
          fail(err) {
            // 调用失败的回调函数
            console.error('弹窗调用失败:', err);
          }
        });
        // } else {
        //   wx.showModal({
        //     title: '提示',
        //     content: '订单中存在茶饮，茶饮内今日送达，营养餐则是明日送达',
        //     success(res) {
        //       console.log(res)
        //       if (res.confirm) {
        //         // 用户点击了确定按钮
        //         that.postOrder()
        //         // 这里可以添加点击确定后的逻辑代码，比如重新让用户输入电话号码等
        //       } else if (res.cancel) {
        //         // 用户点击了取消按钮
        //         console.log('用户点击了取消');
        //         // 这里可以添加点击取消后的逻辑代码，比如关闭弹窗，不做其他操作等
        //       }

        //     },
        //     fail(err) {
        //       // 调用失败的回调函数
        //       console.error('弹窗调用失败:', err);
        //     }
        //   });
        // }

      } else if (Distribution == '快递配送（普通快递）') {
        var userAddress = this.data.userAddress;
        console.log(userAddress);
        if (userAddress == null) {
          wx.showModal({
            title: '提示',
            content: '您还没有默认地址请先去设置默认地址',
            showCancel: false
          });
          return false;
        } else {
          //获取到配送的省
          var province = this.data.userAddress.province;
          //获取到配送的市
          var city = this.data.userAddress.city;
          //获取到配送的区
          var country = this.data.userAddress.country;
          //获取到配送的详细的地址
          var details = this.data.userAddress.details;
          //获取到详细配送地址
          var doderaddress = province + city + country + details;

          this.setData({
            doderaddress: doderaddress
          });
          console.log(doderaddress);
          //获取到收件人
          var name = this.data.userAddress.consignee;
          console.log(name);
          //获取到收件人电话号码
          var phone = this.data.phone;
          console.log(phone);
          var storeid = this.data.mendian.id;
          var tath = this
          console.log(storeid, city)

          // wx.request({
          //   url: 'https://199shq.com/api/remoteCity/getStoreIdQueryRemoteCity',
          //   method: 'get',
          //   header: {
          //     'Content-Type': 'application/json',
          //     'token': wx.getStorageSync('token')
          //   },
          //   data: {
          //     cityName: city,
          //     storeId: storeid
          //   },
          //   success: function (res) {
          //     console.log(res.data.data)
          //     if (res.data.data == '属于偏远市') {
          //       wx.showModal({
          //         title: '提示',
          //         content: '本地区该门店暂不支持快递',
          //         showCancel: false
          //       });
          //       isCanApply = false;
          //       return false;
          //     } else {
          //       isCanApply = true; 
          //       // this.postOrders()
          //     }
          //   },
          //   fail: function (err) {
          //     console.log(err);
          //     isCanApply = false;
          //   }
          // })
          //获取到配送时间
          var date = '快递配送';
          isCanApply = true;
        }
      } else {
        //院内自取不用地址
        var doderaddress = "院内自取";
        this.setData({
          doderaddress: doderaddress
        });
        //配送方式也是院内自取
        var Distribution = "院内自取";
        //获取到取件人姓名
        var name = this.data.name;
        if (name == '') {
          wx.showModal({
            title: '提示',
            content: '请填写收件人的名称',
            showCancel: false
          });
          return false;
        }
        //获取到收件人电话号码
        var phone = this.data.phone;
        if (phone == '') {
          wx.showModal({
            title: '提示',
            content: '请填写收件人的电话',
            showCancel: false
          });
          return false;
        }
        var reg = /^1[3456789]\d{9}$/;
        //用正则表达式验证电话号码是否合格
        if (!reg.test(phone)) {
          wx.showModal({
            title: '提示',
            content: '请填写正确的电话号码',
            showCancel: false
          });
          return false;
        }

        //获取到到店时间
        var date = this.getDistribution();
        // if (date == '日期' || date == '时间') {
        //   wx.showModal({
        //     title: '提示',
        //     content: '请选择合适的到店时间',
        //     showCancel: false
        //   });
        //   return false;
        // }
        // if (!this.data.isRightTime) {
        //   wx.showModal({
        //     title: '提示',
        //     content: '请选择正确的到店时间',
        //     showCancel: false
        //   });
        //   return false;
        // }
        console.log(date); //string
        console.log(555)
        isCanApply = true;
        var pangd = this.data.pangd
        if (pangd) {
          wx.showModal({
            title: '提示',
            content: '今日订的餐将今日领取',
            success(res) {
              console.log(res)
              if (res.confirm) {
                // 用户点击了确定按钮
                that.postOrder()
                // 这里可以添加点击确定后的逻辑代码，比如重新让用户输入电话号码等
              } else if (res.cancel) {
                // 用户点击了取消按钮
                console.log('用户点击了取消');
                // 这里可以添加点击取消后的逻辑代码，比如关闭弹窗，不做其他操作等
              }

            },
            fail(err) {
              // 调用失败的回调函数
              console.error('弹窗调用失败:', err);
            }
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '订单中存在茶饮类，茶饮类今日领取，营养餐则明日领取，自取地址为综合楼一楼西药房对面临床营养服务中心',
            success(res) {
              console.log(res)
              if (res.confirm) {
                // 用户点击了确定按钮
                that.postOrder()
                // 这里可以添加点击确定后的逻辑代码，比如重新让用户输入电话号码等
              } else if (res.cancel) {
                // 用户点击了取消按钮
                console.log('用户点击了取消');
                // 这里可以添加点击取消后的逻辑代码，比如关闭弹窗，不做其他操作等
              }

            },
            fail(err) {
              // 调用失败的回调函数
              console.error('弹窗调用失败:', err);
            }
          });
        }

      }
    } else {
      wx.showModal({
        title: '提示',
        content: '请选择正确的配送方式',
        showCancel: false
      });
      return false;
    }

    if (!isCanApply) {
      return false;
    }

  },

  findaddress: function () {
    var app = getApp();
    var userid = app.globalData.userInfo.wxUserId;
    var that = this
    wx.request({
      url: `https://199shq.com/api/wxuserHospitalAddress/${userid}`, // https://199shq.com
      method: 'PUT',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log('请求成功', res.data);
        var targetId = res.data.data.courtyardId; // 根据实际情况修改字段名
        that.autoSelectByID(targetId);

        var departmentId = res.data.data.departmentId
        var courtyardId = res.data.data.courtyardId
        // var input = res.data.data.address;
        that.setData({
          inputValue: res.data.data.address,
          phone: res.data.data.mobile,
          name: res.data.data.consignee,
          departmentId: departmentId,
        });
        console.log(departmentId)
        that.autoSelectByID6(departmentId)
        that.bindPicker4Changs(targetId)

        that.bindPicker4Changss(departmentId)
        that.autoSelectByID3(floorId)
        that.autoSelectByID(courtyardId)
      },
      fail: function (res) {
        console.log('请求失败', res);
        // 处理失败的情况
      }
    });
  },

  autoSelectByID: function (id) {
    const {
      array2
    } = this.data;
    console.log(id)
    console.log(array2)
    const index = array2.findIndex(item => item.id === id);
    console.log(index)
    if (index !== -1) {
      this.setData({
        index2: index,
        showPicker: true
      });
    }
  },
  bindPicker4Changs: function (id) {
    let that = this;
    wx.request({
      url: `https://199shq.com/api/wxCoupons/getDepartment/` + id,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("楼层信息")
        console.log(res.data);
        let idDataMap4 = {};

        let newData4 = res.data.map(item => {
          idDataMap4[item.id] = item; // 将id和对应数据存入idDataMap
          return item.departmentName; // 只保留院区名称
        }); // 处理返回的数据 // 提取每个对象的 name 属性
        console.log(that.data.index6)
        const array6 = res.data;
        const id = that.data.departmentId
        console.log(id)
        const index = array6.findIndex(item => item.id === id);
        console.log(index)
        const selectedName = res.data[index].departmentName;
        const selectedObject4 = Object.values(idDataMap4).find(obj => obj.departmentName === selectedName);
        console.log(selectedObject4);
        that.setData({
          array6: res.data,
          idDataMap4: idDataMap4,
          selectedObject4: selectedObject4,
          index6: index
          // departmentId: res.data[0].id
        });
        console.log(that.data.array6)
      },
      fail: function (error) {
        console.log(error); // 请求失败的处理
      }
    });


  },
  autoSelectByID6: function (id) {

  },
  bindPicker4Changss: function (id) {

    let that = this;
    wx.request({
      url: `https://199shq.com/api/wxCoupons/getFloor/` + id,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("楼层信息")
        console.log(res.data); // 处理返回的数据
        let newData = res.data.map(item => item.number); // 提取每个对象的 name 属性
        that.setData({
          array3: res.data,
          floorId: res.data[0].id
        });
      },
      fail: function (error) {
        console.log(error); // 请求失败的处理
      }
    });


  },
  autoSelectByID3: function (id) {
    const {
      array3
    } = this.data;
    console.log(array3)
    const index = array3.findIndex(item => item.id === id);
    console.log(index)
    if (index !== -1) {
      this.setData({
        index3: index,
        showPicker: true
      });
      console.log(array6[index])
    }
  },
  addaddress: function () {
    var arr2 = this.data.array2;
    var index2 = this.data.index2;
    console.log(arr2[index2])
    var input = this.data.inputValue;
    console.log(input);
    var arr6 = this.data.array6;
    var index6 = this.data.index6;
    console.log(arr6[index6])
    var arr3 = this.data.array3;
    var index3 = this.data.index3;
    console.log(arr3[index3])
    var phone = this.data.phone;
    console.log(phone)
    var consignee = this.data.name
    console.log(consignee)
    var courtyardId = this.data.courtyardId
    var departmentId = this.data.departmentId
    var floorId = this.data.floorId
    // var doderaddress = arr2[index2] + '-' + arr6[index6] + '-' + arr3[index3] + '-' + input;
    var app = getApp();
    var userid = app.globalData.userInfo.wxUserId;
    const data = {
      address: input,
      floorId: floorId,
      departmentId: departmentId,
      courtyardId: courtyardId,
      courtyard: arr2[index2].id,
      consignee: consignee,
      department: arr6[index6].id,
      floor: arr3[index3].id,
      mobile: phone,
      wxUserId: userid
    }
    wx.request({
      url: 'https://199shq.com/api/wxuserHospitalAddress/save', // https://199shq.com
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: data,
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log('请求成功', res.data);

      },
      fail: function (res) {
        console.log('请求失败', res);
        // 处理失败的情况
      }
    });
  },
  //提交订单存放至数据库
  postOrder: function () {
    var selectedCoupon = this.data.selectedCoupon
    console.log(selectedCoupon)
    this.setData({
      loading: true
    });
    // 执行耗时操作 // 操作完成后恢复按钮状态
    setTimeout(() => {
      this.setData({
        loading: false
      });
    }, 1000);

    //判断是快递配送还是院内自取



    //提交数据到服务端
    //获取输入的给商家留言
    var messg = this.data.messg;
    console.log(messg); //string y
    //获取门店信息
    var storeName = this.data.mendian.name;
    console.log(storeName); //string
    var storeTx = this.data.mendian.storeTximgUrl;
    console.log(storeTx); //string
    //获取门店id
    var storeid = this.data.mendian.id;
    //获取到用户的userid
    var app = getApp();
    var userid = app.globalData.userInfo.wxUserId;
    var openId = app.globalData.userInfo.openId;
    console.log(userid); //number
    //如果有邀请人id则获取id，如果没有则为空
    var inviteid = app.globalData.inviteId;
    var array = this.data.array;
    //生成一个随机的uuID，如果有多个订单则标记多个订单为同一时间创建
    var pattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
    var uuid = pattern.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0,
        v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });

    //循环获取本地购物车中的商品生成不同的订单
    //获取到购物车的长度
    var cartlen = this.data.cart.length;
    //当存在多个订单的时候，获取到所有订单的总价格
    var allprice = this.data.price;
    //在进入循环遍历之前先清空数组内的数据
    app.globalData.cartID = [];
    console.log(app.globalData.cartID);
    const doderaddress = this.data.doderaddress
    var name = this.data.name;
    var phone = this.data.phone;
    var index = this.data.selectedIndex;

    var Distribution = array[index];
    var j = 0;
    for (var i = 0; i < this.data.cart.length; i++) {
      console.log(i);
      //获取到商品的id
      var goods_id = this.data.cart[i].id;
      console.log(this.data.cart[i]); //number
      var specMultipleValue = this.data.cart[i].specMultipleValue
      //获取到商品的数量
      var quantity = this.data.cart[i].quantity;
      console.log(quantity); //number
      //获取到商品的名字
      var goods_name = this.data.cart[i].name;
      var specification = this.data.cart[i].specification
      //获取商品的coveurl
      var goods_coverUrl = this.data.cart[i].coverUrl;
      //获取到商品单价并且计算该商品订单的总价

      var cartprice = this.data.cart[i].cartprice;
      var orderprice = cartprice * quantity;
      console.log(orderprice); //number
      // 处理会员价array 
      var member = this.data.member;
      var memberPrice = this.data.memberPrice;
      if (member === 1 && cartprice > memberPrice) {
        orderprice = orderprice * memberPrice
      }
      var selectedCoupon = this.data.selectedCoupon
      console.log(selectedCoupon)
      const price = ''
      if (selectedCoupon !== undefined && selectedCoupon !== null) {
        orderprice = orderprice - selectedCoupon.discountPrice
        if (orderprice <= 0) {
          orderprice = 0
        }
      }
      var id = ''
      if (selectedCoupon !== '' && selectedCoupon !== null && selectedCoupon !== undefined) {
        id = selectedCoupon.id
      }
      //获取到邀请人的id，并且判断邀请人的id是否为空即判断是否存在邀请人
      var inviteid = getApp().globalData.inviteid;
      var that = this
      if (inviteid == '') {
        console.log("不存在邀请人");
        wx.request({
          url: 'https://199shq.com/api/orders', // https://199shq.com
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          data: {
            //配送地址
            "address": doderaddress,
            //用户名称
            "consignee": name,
            "specMultipleValue": specMultipleValue,
            //用户留言
            "message": messg,
            //用户电话
            "mobile": phone,
            "proCouponId": id,
            //订单总价
            "orderPrice": orderprice,
            //门店名称
            "storeName": storeName,
            //门店头像
            "storeTxImg": storeTx,
            //用户ID
            "wxUserId": userid,
            //配送方式
            "shippingMethod": Distribution,
            //送达时间
            // "deliveryTime":'',
            // "deliveryTime": date,
            //商品id
            "goodsId": goods_id,
            //商品数量
            "goodsNumber": quantity,
            //商品的名字
            "goodsName": goods_name,
            //商品url
            "goodsUrl": goods_coverUrl,
            //邀请人id
            "inviteId": inviteid,
            //门店id
            "storeId": storeid,
            //用户的openid
            "openId": openId,
            //标识同一时间创建的订单的uuid
            "identity": uuid,
            // 商品价格
            "goodsPrice": cartprice,
            "ordersSpecName": specification,

            //  ""
          },
          header: {
            'Content-Type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          success: function (res) {
            console.log('请求成功', res.data);
            if (orderprice <= 0) {
              that.order(res.data.data);
              return;
            }
            // 处理成功响应的数据
            //校验是否从购物车中进入
            if (app.globalData.cat_ID.length > 0) {
              console.log("是从购物车中进入");
              console.log(app.globalData.cat_ID);
              var item = app.globalData.cat_ID;
              for (var i = 0; i < item.length; i++) {
                wx.request({
                  url: `https://199shq.com/api/shoppingCart/${item[i].id}`,
                  method: 'DELETE',
                  header: {
                    'Content-Type': 'application/json',
                    'token': wx.getStorageSync('token')
                  },
                  success: function (res) {
                    console.log(res.data.data);
                  }
                })
              }
            }
            app.globalData.cartID.push(res.data.data);
            console.log(i, cartlen);
            j++;
            console.log(j);
            if (j + 1 == cartlen || cartlen == 1) {
              console.log('遍历到了最后一个单', i);
              console.log(allprice);
              app.globalData.allprice = allprice;
              wx.redirectTo({
                url: `/pages/pays/pays?value=${res.data.data}`
              });
            }
          },
          fail: function (res) {
            console.log('请求失败', res);
            // 处理失败的情况
          }
        });
      } else { //存在邀请人
        console.log("存在邀请人");
        wx.request({
          url: 'https://199shq.com/api/orders',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          data: {
            //配送地址
            "address": doderaddress,
            //用户名称
            "consignee": name,
            //用户留言
            "message": messg,
            //用户电话
            "mobile": phone,
            //订单总价
            "orderPrice": orderprice,
            //门店名称 
            "storeName": storeName,
            "proCouponId": id,
            //门店头像
            "storeTxImg": storeTx,
            //用户ID
            "wxUserId": userid,
            // "deliveryTime":'',
            //配送方式
            "shippingMethod": Distribution,
            //送达时间
            // "deliveryTime": date,
            //商品id
            "goodsId": goods_id,
            //商品数量
            "goodsNumber": quantity,
            //商品的名字
            "goodsName": goods_name,
            //商品url
            "goodsUrl": goods_coverUrl,
            //邀请人id
            "inviteId": inviteid,
            //门店id
            "storeId": storeid,
            //用户的openid
            "openId": openId,
            //邀请人id
            "inviteId": inviteid,
            //标识同一时间创建的订单的uuid
            "identity": uuid,
            //商品价格
            "goodsPrice": cartprice,
            "ordersSpecName": specification,
            "goodsStatus": productStatus
          },
          header: {
            'Content-Type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          success: function (res) {
            console.log('请求成功', res.data);
            // 处理成功响应的数据
            //订单只会调用其中的某一个进行支付
            //校验是否从购物车中进入
            if (app.globalData.cat_ID != '') {
              console.log("是从购物车中进入");
              console.log(app.globalData.cat_ID);
              var id = app.globalData.cat_ID;
              wx.request({
                url: `https://199shq.com/api/shoppingCart/${id}`,
                method: 'DELETE',
                header: {
                  'Content-Type': 'application/json',
                  'token': wx.getStorageSync('token')
                },
                success: function (res) {
                  app.globalData.cat_ID = '';
                  console.log(app.globalData.cat_ID);
                }
              })
            }
            app.globalData.cartID.push(res.data.data);
            j++;
            if (j + 1 == cartlen || cartlen == 1) {
              console.log('遍历到了最后一个单', i);
              app.globalData.allprice = allprice;
              wx.redirectTo({
                url: `/pages/pays/pays?value=${res.data.data}`
              });
            }
          },
          fail: function (res) {
            console.log('请求失败', res);
            // 处理失败的情况
          }
        });
      }
    }
  },


  //订单提交完毕跳转到支付页面
  // wx.navigateTo({
  //   url: '/pages/orderRess/orderRess'
  // });

  order: function (id) {
    console.log(id)
    var selectedCoupon = this.data.selectedCoupon
    wx.request({
      url: `https://199shq.com/api/pay/pay0?orderId=${id}&promotionId=${selectedCoupon.id}`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.state == 20000) {
          wx.redirectTo({
            url: '/pages/pay/pay'
          });
        }
      }
    })
  },
  //获取到用户的地址信息，并且获取出默认地址
  getUserAddress: function () {
    //获取到用户的userid
    var app = getApp();
    var userid = app.globalData.userInfo.wxUserId;
    console.log(userid); //number
    var that = this;
    wx.request({
      url: `https://199shq.com/api/address/isDefault/del/${userid}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data);
        var list = res.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            userAddress: res.data.data,
          })
        }
        if (res.data.data != null) {
          that.setData({
            jgnum: true
          })
        }
      }
    })
  },

  // 定义商品背景颜色的页面高度
  onLoad: function (options) {
    const that = this;
    const observer = wx.createIntersectionObserver(this, {
      thresholds: [0.5],
    });
    observer.relativeToViewport().observe('.sc', function (res) {
      if (res.intersectionRatio > 0) {
        wx.createSelectorQuery().select('#scrollView').boundingClientRect(function (rect) {
          that.setData({
            containerHeight: rect.height,
          });
        }).exec();
      }
    });
  },

  // 查询用户自己的现金优惠券 orderCoupon用于优惠券
  getUserCoupons: function () {
    var that = this;
    //先从本地获取到购车里面的商品信息
    var app = getApp();
    //获取到微信userid
    var UserId = String(app.globalData.userInfo.wxUserId);
    console.log("用户id" + UserId)
    wx.request({
      url: `https://199shq.com/api/couponUse/wxUserId/${UserId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        var orderCoupon = res.data.data;
        console.log(orderCoupon);
        console.log("未使用的优惠券：" + orderCoupon[0].status);
        console.log(this.data.storeID);

        var newDataArray = []; // 创建一个空数组用于存放满足条件的数据     
        orderCoupon.forEach(item => {
          console.log(item.status);
          console.log("this.data.storeID" + this.data.storeID);
          console.log("item.storeId" + item.storeId);
          var storeID = parseInt(this.data.storeID); // 将数据转换为整数类型
          var storeId = parseInt(item.storeId); // 将数据转换为整数类型
          if (item.status === 1 && storeID === storeId && item.discountType === 1) {
            newDataArray.push(item); // 将满足条件的数据推入新数组
          }
        });

        console.log(newDataArray); // 输出满足条件的数据数组
        if (newDataArray.length === 0) {
          // 如果 newDataArray 数组为空，则清空 app.globalData.newDataArray 值
          app.globalData.newDataArray = [];
        } else {
          // 如果 newDataArray 数组不为空，则将第一个元素的 id 赋值给 app.globalData.newDataArray
          app.globalData.newDataArray = newDataArray[0].id;
        }
        // 如果需要更新页面中的数据，可以调用 setData 方法
        this.setData({
          orderCoupon: newDataArray,
        });
        if (newDataArray.length > 0) {
          // 在对应的 js 文件中计算处理数据
          let finalPrice = this.data.price - orderCoupon[0].discountPrice;
          this.setData({
            finalPrice: finalPrice
          });
        }

      }
    })
  },
  coupon: function () {
    this.setData({
      priceMember: this.data.priceMembers
    })
    var storeid = this.data.mendian.id;
    console.log(this.data.cart)
    var categoriesId = this.data.cart[0].categoriesId
    wx.navigateTo({
      url: `/packageA/pages/coupon/coupon?storeid=${storeid}&categoriesId=${categoriesId}`
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var self = this; // 保存当前的上下文
    // 加载当前的页面商品占用的高度
    wx.createSelectorQuery().select('#scrollView').boundingClientRect(function (rect) {
      console.log('scroll-view的高度：', rect.height);
      if (rect.height > 339) {
        self.setData({
          containerHeight: '300'
        })
      }
    }).exec();
    console.log("选中的优惠券：", this.data.selectedCoupon);
    // this.getUserAddress();
    console.log(options);
    this.setData({
      storeID: options.value,
      prices: options.prices,
      specification: options.specification,
      productStatus: options.productStatus,
      canCoupon: options.canCoupon,
      specMultipleValue: options.specMultipleValue,
    });
    // if (options.categoriesId == '711460724') {
    //   this.setData({
    //     array:['院内配送']
    //   })
    //   console.log(thia.data.array)
    // }
    console.log(this.data)
    this.getSSnc();
    // this.showMarker();
    this.countprice();
    this.getMendian();
    this.getUserCoupons();
    this.optionChange();
    this.loadProductList();
    //     this.showMarker();
    //   },

    //   showMarker() {
    //     const address = this.data.address;

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('支付页显示，检查选中的优惠券');
    const {
      selectedCoupon,
      priceMember
    } = this.data;

    console.log("进入");
    console.log("当前价格：", priceMember);
    console.log("选中的优惠券：", selectedCoupon);

    let newPrice = priceMember; // 默认价格不变

    // 只有当优惠券存在且有 discountPrice 时才减去
    if (selectedCoupon && selectedCoupon.discountPrice != null) {
      const discount = parseFloat(selectedCoupon.discountPrice);
      if (!isNaN(discount)) {
        newPrice = Math.max(0, priceMember - discount); // 防止负数
      }
    } else {
      console.log("无有效优惠券，不减价");
    }

    // 更新最终价格
    this.setData({
      priceMember: Number(newPrice.toFixed(2)) // 保留两位小数
    });

    console.log("更新后的价格：", this.data.priceMember);

    // 执行其他逻辑
    this.getUserAddress();
    this.findaddress();
    this.optionChange();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})